package com.ihd.ihardware.view.tzc.me.view;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.ihd.ihardware.R;
import com.ihd.ihardware.app.MyApplication;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.databinding.ActivityAddMemberBinding;
import com.ihd.ihardware.pojo.EmptyRes;
import com.ihd.ihardware.pojo.FileRes;
import com.ihd.ihardware.pojo.MembersRes;
import com.ihd.ihardware.pojo.OPValue;
import com.ihd.ihardware.pojo.UserInfoRes;
import com.ihd.ihardware.view.tzc.me.viewmodel.AddMemberViewModel;

import org.jaaksi.pickerview.dataset.OptionDataSet;
import org.jaaksi.pickerview.picker.OptionPicker;
import org.jaaksi.pickerview.picker.TimePicker;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.wowjoy.commonlibrary.adapter.DialogListAdapter;
import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.ImageUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import cn.wowjoy.commonlibrary.widget.MDialog;

public class AddMemberActivity extends BaseActivity<ActivityAddMemberBinding, AddMemberViewModel> {
    public static final int PHOTO_PICKED_WITH_PATH = 3022;
    public static final int CAMERA_WITH_DATA = 3023;
    private OptionPicker mRPicker;
    private List<OPValue> relation = new ArrayList<>();
    private OptionPicker mHPicker;
    private List<OPValue> height = new ArrayList<>();
    private OptionPicker mWPicker;
    private List<OPValue> weight = new ArrayList<>();
    private TimePicker mTimePicker;
    private MDialog mBottomDG;

    private String avatar;
    private int sex = 2;
    private int rela = 1;
    private String birth = "1990-01-01";
    private String h;
    private String w;

    private MembersRes.DataBean md;
    private UserInfoRes.DataBean ud;

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(true).init();
        binding.mtitlebar.setTitle("添加新成员");
        binding.mtitlebar.setLeftBack(this);

        relation.add(new OPValue("爱人"));
        relation.add(new OPValue("爸爸"));
        relation.add(new OPValue("妈妈"));
        relation.add(new OPValue("儿子"));
        relation.add(new OPValue("女儿"));
        relation.add(new OPValue("朋友"));
        relation.add(new OPValue("其他"));
        for (float i = 30.0f; i < 180.0f; i += 0.5f) {
            weight.add(new OPValue(new BigDecimal(i).setScale(1, 4).toString()));
        }
        for (int i = 80; i < 251; i++) {
            height.add(new OPValue(String.valueOf(i)));
        }

        ud = new Gson().fromJson(SPUtils.getString(AppConstans.USER_INFO, ""), UserInfoRes.DataBean.class);
        md = (MembersRes.DataBean) getIntent().getSerializableExtra("member");
        if (md != null) {
            avatar = md.getAvatar();
            sex = md.getSex();
            rela = md.getRelation();
            birth = md.getBirthday();
            h = md.getHeight();
            w = md.getWeight();

            if (!TextUtils.isEmpty(md.getAvatar())) {
                Glide.with(getApplicationContext())
                        .load(Uri.parse(avatar))
                        .apply(RequestOptions.circleCropTransform())
                        .into(binding.head);
            }
            if (sex == 1) {
                binding.female.setTextColor(getResources().getColor(R.color.C_898B90));
                binding.female.setBackgroundResource(R.drawable.corners_left_e8e9f0);
                binding.male.setTextColor(getResources().getColor(R.color.C_FFFFFF));
                binding.male.setBackgroundResource(R.drawable.corners_right_46a5f9);
            } else {
                binding.female.setTextColor(getResources().getColor(R.color.C_FFFFFF));
                binding.female.setBackgroundResource(R.drawable.corners_left_9065f9);
                binding.male.setTextColor(getResources().getColor(R.color.C_898B90));
                binding.male.setBackgroundResource(R.drawable.corners_right_e8e9f0);
            }

            binding.relation.setText(relation.get(rela - 1).getValue());
            binding.birth.setText(birth);
            binding.height.setText(h);
            binding.weight.setText(w);
        }

        setRx(AppConstans.UPDATE, new BaseConsumer<FileRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(AddMemberActivity.this);
            }

            @Override
            protected void onSuccess(FileRes mLiveData) {
                DialogUtils.dismiss(AddMemberActivity.this);
                Glide.with(getApplicationContext())
                        .load(Uri.parse(mLiveData.getData().getUrl()))
                        .apply(RequestOptions.circleCropTransform())
                        .into(binding.head);
                avatar = mLiveData.getData().getUrl();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(AddMemberActivity.this, error.getMessage());
                DialogUtils.dismiss(AddMemberActivity.this);
            }
        });

        binding.head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomDG = DialogUtils.BottomListDialog(AddMemberActivity.this, Arrays.asList("拍照", "从相册中选择"), new DialogListAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, String data) {
                        mBottomDG.cancel();
                        if (data.equals("拍照")) {
                            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri imguri = Uri.fromFile(new File(AppConstans.BASE_PATH + AppConstans.HEAD_PATH));
                            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imguri);
                            startActivityForResult(openCameraIntent, CAMERA_WITH_DATA);
                        } else {
                            Intent intent = new Intent(Intent.ACTION_PICK);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, PHOTO_PICKED_WITH_PATH);
                        }
                    }
                });
            }
        });

        binding.female.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.female.setTextColor(getResources().getColor(R.color.C_FFFFFF));
                binding.female.setBackgroundResource(R.drawable.corners_left_9065f9);
                binding.male.setTextColor(getResources().getColor(R.color.C_898B90));
                binding.male.setBackgroundResource(R.drawable.corners_right_e8e9f0);
                sex = 2;
            }
        });

        binding.male.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.female.setTextColor(getResources().getColor(R.color.C_898B90));
                binding.female.setBackgroundResource(R.drawable.corners_left_e8e9f0);
                binding.male.setTextColor(getResources().getColor(R.color.C_FFFFFF));
                binding.male.setBackgroundResource(R.drawable.corners_right_46a5f9);
                sex = 1;
            }
        });

        mHPicker = new OptionPicker.Builder(this, 1, new OptionPicker.OnOptionSelectListener() {
            @Override
            public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {
                binding.height.setText(height.get(selectedPosition[0]).getValue());
                h = binding.height.getText().toString();
            }
        }).create();

        mHPicker.setDataWithValues(height, "165");

        binding.height.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHPicker.show();
            }
        });

        mWPicker = new OptionPicker.Builder(this, 1, new OptionPicker.OnOptionSelectListener() {
            @Override
            public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {
                binding.weight.setText(weight.get(selectedPosition[0]).getValue());
                w = binding.weight.getText().toString();
            }
        }).create();

        mWPicker.setDataWithValues(weight, "50.0");

        binding.weight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWPicker.show();
            }
        });

        mRPicker = new OptionPicker.Builder(this, 1, new OptionPicker.OnOptionSelectListener() {
            @Override
            public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {
                binding.relation.setText(relation.get(selectedPosition[0]).getValue());
                rela = selectedPosition[0] + 1;
            }
        }).create();

        mRPicker.setDataWithValues(relation, "爱人");

        binding.relation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRPicker.show();
            }
        });

        try {
            mTimePicker = new TimePicker.Builder(this, TimePicker.TYPE_YEAR | TimePicker.TYPE_MONTH | TimePicker.TYPE_DAY, new TimePicker.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(TimePicker picker, Date date) {
                    binding.birth.setText(new SimpleDateFormat("yyyy-MM-dd").format(date));
                    birth = binding.birth.getText().toString();
                }
            }).setRangDate(new SimpleDateFormat("yyyy-MM-dd").parse("1900-01-01").getTime(), new Date().getTime()).create();
        } catch (ParseException e) {
        }

        binding.birth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mTimePicker.setSelectedDate(new SimpleDateFormat("yyyy-MM-dd").parse("1990-01-01").getTime());
                } catch (ParseException e) {
                }
                mTimePicker.show();
            }
        });

        binding.confirmTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(birth))
                    ToastUtils.showShort(AddMemberActivity.this, "请选择出生年月日");
                else if (TextUtils.isEmpty(h))
                    ToastUtils.showShort(AddMemberActivity.this, "请选择身高");
                else if (TextUtils.isEmpty(w))
                    ToastUtils.showShort(AddMemberActivity.this, "请选择体重");
                else {
                    if (md != null)
                        viewModel.editMember(avatar, rela, sex, birth, h, w, md.getMemberId());
                    else
                        viewModel.AddMember(avatar, rela, sex, birth, h, w);
                }
            }
        });

        setRx(AppConstans.ADDMEMBER, new BaseConsumer<MembersRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(AddMemberActivity.this);
            }

            @Override
            protected void onSuccess(MembersRes mLiveData) {
                DialogUtils.dismiss(AddMemberActivity.this);
                MyApplication.membersData.clear();
                MembersRes.DataBean md = new MembersRes.DataBean();
                md.setAvatar(ud.getAvatar());
                md.setBirthday(ud.getBirthDay());
                md.setHeight(ud.getHeight());
                md.setMemberId("");
                md.setWeight(ud.getWeight());
                md.setUserId(ud.getUserId());
                md.setSex(ud.getSex());
                md.setRelation(0);
                MyApplication.membersData.add(md);
                if (mLiveData.getData() != null && mLiveData.getData().size() > 0)
                    MyApplication.membersData.addAll(mLiveData.getData());
                MyApplication.membersData.add(new MembersRes.DataBean());
                viewModel.handWeighing(mLiveData.getData().get(mLiveData.getData().size() - 1).getMemberId(), w);
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(AddMemberActivity.this, error.getMessage());
                DialogUtils.dismiss(AddMemberActivity.this);
            }
        });

        setRx(AppConstans.HANDWEIGHT, new BaseConsumer<EmptyRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(EmptyRes mLiveData) {
                finish();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(AddMemberActivity.this, error.getMessage());
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_member;
    }

    @Override
    protected Class getViewModelClass() {
        return AddMemberViewModel.class;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String path = AppConstans.BASE_PATH + AppConstans.HEAD_PATH_S;
            switch (requestCode) {
                case CAMERA_WITH_DATA:
                    File f = ImageUtils.zoomImageFile(AppConstans.BASE_PATH + AppConstans.HEAD_PATH, path, 1080);
                    if (f != null)
                        viewModel.updateHead(f);
                    break;
                case PHOTO_PICKED_WITH_PATH:
                    final Uri uri = data.getData();
                    if (uri != null) {
                        File f0 = ImageUtils.zoomImageFile(ImageUtils.uri2path(this, uri), path, 1080);
                        if (f0 != null)
                            viewModel.updateHead(f0);
                    }
                    break;
            }
        }
    }
}
